<template>
  <div class="app-container">
    <a-form :model="queryParams" ref="queryRef" layout="inline" v-show="showSearch">
      <a-form-item label="菜单名称" field="menuName">
        <a-input
            size="small"
            v-model="queryParams.menuName"
            placeholder="请输入菜单名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </a-form-item>
      <a-form-item label="状态" field="status">
        <a-select v-model="queryParams.status" size="small" placeholder="菜单状态" clearable>
          <a-option
              v-for="dict in sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </a-select>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" size="small" class="button-margin-right" @click="handleQuery">
          <icon-Search/>
          搜索
        </a-button>
        <a-button size="small" @click="resetQuery">
          <icon-loop/>
          重置
        </a-button>
      </a-form-item>
    </a-form>

    <a-row :gutter="10" class="mb8">
      <a-col :span="1.5">
        <a-button
            type="primary"
            plain
            size="small"
            @click="handleAdd"
            v-hasPermi="['system:menu:add']"
        ><icon-plus/>新增
        </a-button>
      </a-col>
      <a-col :span="1.5">
        <a-button
            @click="toggleExpandAll"
        ><icon-mind-mapping />展开/折叠
        </a-button>
      </a-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </a-row>

    <a-table
        v-if="refreshTable"
        v-loading="loading"
        :data="menuList"
        row-key="menuId"
        :default-expand-all-rows="isExpandAll"
        :pagination="false"
    >
      <template #columns>
        <a-table-column data-index="menuName" title="菜单名称" :show-overflow-tooltip="true" width="160"></a-table-column>
        <a-table-column data-index="icon" title="图标" align="center" width="100">
          <template #cell="{record}">
            <svg-icon :icon-class="record.icon"/>
          </template>
        </a-table-column>
        <a-table-column data-index="orderNum" title="排序" width="60"></a-table-column>
        <a-table-column data-index="perms" title="权限标识" :show-overflow-tooltip="true"></a-table-column>
        <a-table-column data-index="component" title="组件路径" :show-overflow-tooltip="true"></a-table-column>
        <a-table-column data-index="status" title="状态" width="80">
          <template #cell="{record}">
            <dict-tag :options="sys_normal_disable" :value="record.status"/>
          </template>
        </a-table-column>
        <a-table-column title="创建时间" align="center" data-index="createTime">
          <template #cell="{record}">
            <span>{{ parseTime(record.createTime) }}</span>
          </template>
        </a-table-column>
        <a-table-column title="操作" align="center" width="280" class-name="small-padding fixed-width">
          <template #cell="{record}">
            <a-button
                type="text"
                size="small"
                @click="handleUpdate(record)"
                v-hasPermi="['system:menu:edit']"
            >
              <icon-edit/>
              修改
            </a-button>
            <a-button
                type="text"
                size="small"
                @click="handleAdd(record)"
                v-hasPermi="['system:menu:add']"
            >
              <icon-plus/>
              新增
            </a-button>
            <a-button
                type="text"
                size="small"
                @click="handleDelete(record)"
                v-hasPermi="['system:menu:remove']"
            >
              <icon-delete/>
              删除
            </a-button>
          </template>
        </a-table-column>
      </template>
    </a-table>

    <!-- 添加或修改菜单对话框 -->
    <a-drawer :visible="menuDrawerVisible" @ok="handleMenuOk" @cancel="handleMenuCancel" unmountOnClose :width="540">
      <template #title>
        <h4>{{ title }}</h4>
      </template>
      <a-form ref="menuRef" :model="form" :rules="rules" label-width="100px">
        <a-row>
          <a-col :span="24">
            <a-form-item label="上级菜单">
              <el-tree-select
                  v-model="form.parentId"
                  :data="menuOptions"
                  :props="{ value: 'menuId', label: 'menuName', children: 'children' }"
                  value-key="menuId"
                  placeholder="选择上级菜单"
                  check-strictly
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="菜单类型" field="menuType">
              <a-radio-group v-model="form.menuType">
                <a-radio value="M">目录</a-radio>
                <a-radio value="C">菜单</a-radio>
                <a-radio value="F">按钮</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="24" v-if="form.menuType != 'F'">
            <a-form-item label="菜单图标" field="icon">
              <el-popover
                  placement="bottom-start"
                  :width="540"
                  v-model:visible="showChooseIcon"
                  trigger="click"
                  @show="showSelectIcon"
              >
                <template #reference>
                  <a-input v-model="form.icon" placeholder="点击选择图标" @click="showSelectIcon"
                            v-click-outside="hideSelectIcon" readonly>
                    <template #prefix>
                      <svg-icon
                          v-if="form.icon"
                          :icon-class="form.icon"
                          class="el-input__icon"
                          style="height: 32px;width: 16px;"
                      />
                      <el-icon v-else style="height: 32px;width: 16px;">
                        <search/>
                      </el-icon>
                    </template>
                  </a-input>
                </template>
                <icon-select ref="iconSelectRef" @selected="selected"/>
              </el-popover>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="菜单名称" field="menuName">
              <a-input v-model="form.menuName" placeholder="请输入菜单名称"/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="显示排序" field="orderNum">
              <a-input-number v-model="form.orderNum" controls-position="right" :min="0"/>
            </a-form-item>
          </a-col>
          <a-col :span="24" v-if="form.menuType != 'F'">
            <a-form-item>
              <template #label>
                        <span>
                           <el-tooltip content="选择是外链则路由地址需要以`http(s)://`开头" placement="top">
                              <el-icon><question-filled/></el-icon>
                           </el-tooltip>是否外链
                        </span>
              </template>
              <a-radio-group v-model="form.isFrame">
                <a-radio value="0">是</a-radio>
                <a-radio value="1">否</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="24" v-if="form.menuType != 'F'">
            <a-form-item field="path">
              <template #label>
                        <span>
                           <el-tooltip content="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头" placement="top">
                              <el-icon><question-filled/></el-icon>
                           </el-tooltip>
                           路由地址
                        </span>
              </template>
              <a-input v-model="form.path" placeholder="请输入路由地址"/>
            </a-form-item>
          </a-col>
          <a-col :span="24" v-if="form.menuType == 'C'">
            <a-form-item field="component">
              <template #label>
                        <span>
                           <el-tooltip content="访问的组件路径，如：`system/user/index`，默认在`views`目录下" placement="top">
                              <el-icon><question-filled/></el-icon>
                           </el-tooltip>
                           组件路径
                        </span>
              </template>
              <a-input v-model="form.component" placeholder="请输入组件路径"/>
            </a-form-item>
          </a-col>
          <a-col :span="24" v-if="form.menuType != 'M'">
            <a-form-item>
              <a-input v-model="form.perms" placeholder="请输入权限标识" maxlength="100"/>
              <template #label>
                        <span>
                           <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)"
                                       placement="top">
                              <el-icon><question-filled/></el-icon>
                           </el-tooltip>
                           权限字符
                        </span>
              </template>
            </a-form-item>
          </a-col>
          <a-col :span="24" v-if="form.menuType == 'C'">
            <a-form-item>
              <a-input v-model="form.query" placeholder="请输入路由参数" maxlength="255"/>
              <template #label>
                        <span>
                           <el-tooltip content='访问路由的默认传递参数，如：`{"id": 1, "name": "ry"}`' placement="top">
                              <el-icon><question-filled/></el-icon>
                           </el-tooltip>
                           路由参数
                        </span>
              </template>
            </a-form-item>
          </a-col>
          <a-col :span="24" v-if="form.menuType == 'C'">
            <a-form-item>
              <template #label>
                        <span>
                           <el-tooltip content="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致" placement="top">
                              <el-icon><question-filled/></el-icon>
                           </el-tooltip>
                           是否缓存
                        </span>
              </template>
              <a-radio-group v-model="form.isCache">
                <a-radio value="0">缓存</a-radio>
                <a-radio value="1">不缓存</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="24" v-if="form.menuType != 'F'">
            <a-form-item>
              <template #label>
                        <span>
                           <el-tooltip content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问" placement="top">
                              <el-icon><question-filled/></el-icon>
                           </el-tooltip>
                           显示状态
                        </span>
              </template>
              <a-radio-group v-model="form.visible">
                <a-radio
                    v-for="dict in sys_show_hide"
                    :value="dict.value"
                    :label="dict.value"
                >{{ dict.label }}
                </a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="24" v-if="form.menuType != 'F'">
            <a-form-item>
              <template #label>
                        <span>
                           <el-tooltip content="选择停用则路由将不会出现在侧边栏，也不能被访问" placement="top">
                              <el-icon><question-filled/></el-icon>
                           </el-tooltip>
                           菜单状态
                        </span>
              </template>
              <a-radio-group v-model="form.status">
                <a-radio
                    v-for="dict in sys_normal_disable"
                    :value="dict.value"
                    :label="dict.value"
                >{{ dict.label }}
                </a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-drawer>
  </div>
</template>

<script setup name="Menu">
import {addMenu, delMenu, getMenu, listMenu, updateMenu} from "@/api/system/menu";
import SvgIcon from "@/components/SvgIcon";
import IconSelect from "@/components/IconSelect";
import {ClickOutside as vClickOutside} from 'element-plus'
import {getCurrentInstance, reactive, ref, toRefs} from "vue";

const {proxy} = getCurrentInstance();
const {sys_show_hide, sys_normal_disable} = proxy.useDict("sys_show_hide", "sys_normal_disable");

const menuList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const menuOptions = ref([]);
const isExpandAll = ref(false);
const refreshTable = ref(true);
const showChooseIcon = ref(false);
const iconSelectRef = ref(null);
const direction = ref('rtl')
const menuDrawerVisible = ref(false)

const data = reactive({
  form: {},
  queryParams: {
    menuName: undefined,
    visible: undefined
  },
  rules: {
    menuName: [{required: true, message: "菜单名称不能为空", trigger: "blur"}],
    orderNum: [{required: true, message: "菜单顺序不能为空", trigger: "blur"}],
    path: [{required: true, message: "路由地址不能为空", trigger: "blur"}]
  },
});

const {queryParams, form, rules} = toRefs(data);

const handleMenuOk = () => {
  submitForm()
};
const handleMenuCancel = () => {
  menuDrawerVisible.value = false;
}

/** 查询菜单列表 */
function getList() {
  loading.value = true;
  listMenu(queryParams.value).then(response => {
    menuList.value = proxy.handleTree(response.data, "menuId");
    loading.value = false;
  });
}

/** 查询菜单下拉树结构 */
function getTreeselect() {
  menuOptions.value = [];
  listMenu().then(response => {
    const menu = {menuId: 0, menuName: "主类目", children: []};
    menu.children = proxy.handleTree(response.data, "menuId");
    menuOptions.value.push(menu);
  });
}

/** 取消按钮 */
function cancel() {
  menuDrawerVisible.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    menuId: undefined,
    parentId: 0,
    menuName: undefined,
    icon: undefined,
    menuType: "M",
    orderNum: undefined,
    isFrame: "1",
    isCache: "0",
    visible: "0",
    status: "0"
  };
  proxy.resetForm("menuRef");
}

/** 展示下拉图标 */
function showSelectIcon() {
  iconSelectRef.value.reset();
  showChooseIcon.value = true;
}

/** 选择图标 */
function selected(name) {
  form.value.icon = name;
  showChooseIcon.value = false;
}

/** 图标外层点击隐藏下拉列表 */
function hideSelectIcon() {
  showChooseIcon.value = false;
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  getTreeselect();
  if (row != null && row.menuId) {
    form.value.parentId = row.menuId;
  } else {
    form.value.parentId = 0;
  }
  menuDrawerVisible.value = true;
  title.value = "添加菜单";
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  await getTreeselect();
  getMenu(row.menuId).then(response => {
    form.value = response.data;
    menuDrawerVisible.value = true;
    title.value = "修改菜单";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["menuRef"].validate(valid => {
    if (!valid) {
      if (form.value.menuId != undefined) {
        updateMenu(form.value).then(response => {
          proxy.$message.success("修改成功");
          menuDrawerVisible.value = false;
          getList();
        });
      } else {
        addMenu(form.value).then(response => {
          proxy.$message.success("新增成功");
          menuDrawerVisible.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$confirm('是否确认删除名称为"' + row.menuName + '"的数据项?').then(function () {
    return delMenu(row.menuId);
  }).then(() => {
    getList();
    proxy.$message.success("删除成功");
  }).catch(() => {
  });
}

getList();
</script>
